package com.health.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.health.common.common.ErrorCode;
import com.health.common.exception.BusinessException;
import com.health.common.model.vo.UserKeyVO;
import com.health.common.service.util.SDKUtils;
import com.health.user.mapper.HospitalMapper;
import com.health.user.mapper.PatientMapper;
import com.health.user.model.dto.user.PatientRegisterRequest;
import com.health.user.model.entity.Hospital;
import com.health.user.model.entity.Patient;
import com.health.user.service.PatientService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.v3.codec.ContractCodecException;
import org.fisco.bcos.sdk.v3.model.TransactionReceipt;
import org.fisco.bcos.sdk.v3.transaction.manager.AssembleTransactionProcessor;
import org.fisco.bcos.sdk.v3.transaction.model.exception.TransactionBaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.logging.LoggingRebinder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.health.common.constant.ContractConstants.ADD_PATIENT;

/**
* @author zhexueqi
* @description 针对表【patient(患者表)】的数据库操作Service实现
* @createDate 2024-08-25 01:31:01
*/
@Service
@Slf4j
public class PatientServiceImpl extends ServiceImpl<PatientMapper, Patient>
    implements PatientService {

    @Resource
    private SDKUtils sdkUtils;
    @Value("${system.contract.contractName}")
    private String CONTRACT_NAME;

    @Value("${system.contract.address}")
    private String CONTRACT_ADDRESS;

    @Value("${system.contract.abi}")
    private String ABI;
    @Value("${system.contract.bin}")
    private String BIN;

    @Resource
    private HospitalMapper hospitalMapper;
    @Autowired
    private LoggingRebinder loggingRebinder;


    @Override
    public void createPatientToMysql(PatientRegisterRequest userRegisterRequest) {
        //判断是否注册
        isRegistered(userRegisterRequest.getUserAccount());
        Patient patient = new Patient();
        patient.setPatientAccount(userRegisterRequest.getUserAccount());
        patient.setPatientName(userRegisterRequest.getName());
        patient.setPhone(userRegisterRequest.getPhone());
        patient.setCardId(userRegisterRequest.getCardId());
        patient.setGender(userRegisterRequest.getGender());
        if (!save(patient)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"注册失败");
        }
    }

    private void isRegistered(String userAccount) {
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("patient_account",userAccount);
        if (count(queryWrapper) > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户已注册");
        }
    }


    /**
     * 创建区块链患者用户
     * @param userKeyVO
     * @param userAccount
     * @throws TransactionBaseException
     * @throws ContractCodecException
     */
    @Override
    public void createPatient(UserKeyVO userKeyVO, String userAccount) throws TransactionBaseException, ContractCodecException {
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("patient_account",userAccount);
        Patient patient = this.getOne(queryWrapper);

        if (patient == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在");
        }

        List<Object> funcParams = new ArrayList<>();
        funcParams.add(userKeyVO.getAddress());
        funcParams.add(patient.getPatientName());
        funcParams.add(patient.getCardId());
        funcParams.add(patient.getPhone());

        AssembleTransactionProcessor assembleTransactionProcessor = sdkUtils.transactionProcessor(userKeyVO.getPrivateKey());
        TransactionReceipt transactionReceipt = assembleTransactionProcessor.sendTransactionAndGetReceiptByContractLoader(CONTRACT_NAME, CONTRACT_ADDRESS, ADD_PATIENT, funcParams);
        if (!transactionReceipt.isStatusOK()){
            throw new BusinessException(ErrorCode.CONTRACT_ERROR,"区块链注册失败");
        }
        log.info("区块链注册成功，交易哈希为：{}",transactionReceipt.getTransactionHash());
    }

    @Override
    @Transactional
    public void createHospital(UserKeyVO userKeyVO, String userAccount) throws TransactionBaseException, ContractCodecException {
        QueryWrapper<Hospital> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hospital_account",userAccount);
        Hospital hospital = hospitalMapper.selectOne(queryWrapper);
        if (hospital == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在");
        }
        List<Object> funcParams = new ArrayList<>();
        funcParams.add(hospital.getHospitalName());
        funcParams.add(hospital.getCoord());
        funcParams.add(hospital.getContactInfo());
        funcParams.add(userKeyVO.getAddress());
        AssembleTransactionProcessor assembleTransactionProcessor = sdkUtils.transactionProcessor(userKeyVO.getPrivateKey());

        TransactionReceipt transactionReceipt = assembleTransactionProcessor.sendTransactionAndGetReceiptByContractLoader(CONTRACT_NAME, CONTRACT_ADDRESS, "addHospital1", funcParams);
        log.info("交易Message:{}",transactionReceipt.getMessage());
        if (!transactionReceipt.isStatusOK()){
            throw new BusinessException(ErrorCode.CONTRACT_ERROR,"区块链注册失败");
        }
        log.info("区块链注册成功，交易哈希为：{}",transactionReceipt.getTransactionHash());
    }
}




